﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.Common;
using Microsoft.Practices.EnterpriseLibrary.Data;
using DuJianliang.ApplicationPlatform.Common;

namespace DuJianliang.ApplicationPlatform.UserPermission
{
    public partial class SelectDept : System.Web.UI.Page
    {
        UserPermissionBll userPermissionBll = new UserPermissionBll();

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                InitTreeView();                
            }
        }

        private void InitTreeView()
        {
            tvDept.Nodes.Clear();
            TreeNode node = new TreeNode();
            node.Value = "0";
            node.Text = "部门";
            node.Target = "0";
            tvDept.Nodes.Add(node);

            DataTable dataTable = userPermissionBll.GetDeptDataTable();
            InitTreeNode(dataTable, "0", node);
            tvDept.Nodes[0].Selected = true;
            tvDept.ExpandAll();

            tvDept_SelectedNodeChanged(null, null);
        }

        private void InitTreeNode(DataTable dataTable, string deptID, TreeNode treeNode)
        {
            DataRow[] dataRows = dataTable.Select(string.Format("ParentDeptID={0}", deptID));
            foreach (DataRow dataRow in dataRows)
            {
                TreeNode node = new TreeNode();
                node.Text = dataRow["DeptName"].ToString();
                node.Value = dataRow["DeptID"].ToString();
                node.Target = dataRow["DeptLevel"].ToString();

                treeNode.ChildNodes.Add(node);
                InitTreeNode(dataTable, node.Value, node);
            }
        }

        protected void tvDept_SelectedNodeChanged(object sender, EventArgs e)
        {
            TreeNode node = tvDept.SelectedNode;
            if (node != null && !node.Value.Equals("0"))
            {
                string deptfullname = userPermissionBll.GetDeptFullName(node.Value);
                string returnValue = node.Value + "|" + deptfullname;
                Response.Write("<script>window.returnValue='" + returnValue + "';window.opener = null;window.open('', '_self', '');window.close();</script>");
            }
        }
    }
}